//
//  MainViewController.m
//  CSLeftSlideDemo
//
//  Created by LCS on 16/2/11.
//  Copyright © 2016年 LCS. All rights reserved.
//

#import "MainViewController.h"
#import "UIBarButtonItem+Extensions.h"
#import "Constants.h"

#import "BPMessagesViewController.h"

#import "BPComboTableViewCell.h"
#import "ImageViewPlayer.h"
#import "BPAdImageView.h"

#import "BPComboViewController.h"
#import <UIImageView+WebCache.h>

@interface MainViewController () <UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UIScrollView *adScroolV;
@property (strong, nonatomic) NSArray *data;
@property (strong, nonatomic) UITableView *comboTableView;

@end

@implementation MainViewController

+ (void)initialize {
    
    UINavigationBar *bar = [UINavigationBar appearance];
    // 此处设置导航栏背景图片

    [bar setBackgroundImage:[UIImage imageNamed:@"barImg"] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
    // 设置导航条字体
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[NSFontAttributeName] = [UIFont systemFontOfSize:20];
    dict[NSForegroundColorAttributeName] = [UIColor colorWithRed:0xff / 255.0 green:0xff / 255.0 blue:0xff / 255.0 alpha:1.0];
    [bar setTitleTextAttributes:dict];
    
    UIImage *image = [UIImage imageNamed:@"back_w"];
    
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    bar.backIndicatorImage = image;
    
    bar.backIndicatorTransitionMaskImage = image;
    
    // 设置返回按钮颜色
    bar.tintColor = [UIColor whiteColor];
    
    //将底部边框消除
    
    [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
    
    // 把返回按钮的文字移除
    UIBarButtonItem *item = [UIBarButtonItem appearance];
    
    // 位置
    [item setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -64) forBarMetrics:UIBarMetricsDefault];

}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"贝贝摄影";
    self.automaticallyAdjustsScrollViewInsets = NO;
    //左边BarButtonItem
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:@"user" highLightImage:@"user" target:self action:@selector(onClickLeftItem)];
    //右边BarButtonItem
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:@"message" highLightImage:@"message" target:self action:@selector(onClickRightItem)];
    
    //获取数据
    [self getComboData];
    
    //设置套餐的tableView
    [self setupCombo];
}

- (void)onClickLeftItem{
    //发送通知，执行侧滑
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationLeftSlide object:nil];
}

- (void)onClickRightItem {
    //拦截未登录的情况
    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"login"]) {
        BPMessagesViewController *messageVC = [[BPMessagesViewController alloc]init];
        [self.navigationController pushViewController:messageVC animated:YES];
    }
    else {
        [SVProgressHUD showInfoWithStatus:@"请先登录"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }
}

- (void)getComboData {
    [SVProgressHUD showWithStatus:@"读取中..."];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                      @"text/html",
                                                      @"image/jpeg",
                                                      @"image/png",
                                                      @"application/octet-stream",
                                                      @"text/json",
                                                      nil];
    
    [mgr POST:[NSString stringWithFormat:@"%@?c=Package&&a=pList",requestURL] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *state = responseObject[@"state"];
        if ([state isEqualToString:@"SUCCESS"]) {
            NSLog(@"套餐列表 %@", responseObject[@"data"]);
            self.data = responseObject[@"data"];
            [SVProgressHUD dismiss];
            [self.comboTableView reloadData];
        }
        else {
            
            [SVProgressHUD showInfoWithStatus:@"数据错误"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showInfoWithStatus:@"请求失败"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }];
}



- (void)setupCombo {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    
    [mgr POST:[NSString stringWithFormat:@"%@?c=Ad&&a=pList",requestURL]
     parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
         
     }
      success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          if ([responseObject[@"state"] isEqualToString:@"SUCCESS"]) {
              NSLog(@"广告 %@", responseObject[@"data"]);
              //设置广告轮播器
              UIView *adView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenW, screenW / 375.0 * 150 + 10)];
              adView.backgroundColor = [UIColor clearColor];
              
              ImageViewPlayer *imgViewPlayer = [ImageViewPlayer imageViewPlayer];
              imgViewPlayer.frame = CGRectMake(0, 0, screenW - 20, screenW / 375.0 * 150);
              imgViewPlayer.layer.cornerRadius = 8;
              imgViewPlayer.layer.masksToBounds = YES;
              NSArray *ads = responseObject[@"data"];
              NSMutableArray *imgs = [NSMutableArray array];
              for (NSDictionary *ad in ads) {
                  BPAdImageView *imgV = [[BPAdImageView alloc]init];
                  [imgV sd_setImageWithURL:[NSURL URLWithString:ad[@"img"][0]] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
                  //根据图片的点击类型设置不同的点击事件
                  NSInteger clickType = [ad[@"clickType"] integerValue];
                  //clickType:0 不可点击 1:跳转url 2:套餐
                  if (clickType) {
                      imgV.userInteractionEnabled = YES;
                      switch (clickType) {
                          case 1:
                          {
                              NSString *url = ad[@"link_url"];
                              NSString *title = ad[@"title"];
                              imgV.clickAction = ^(){
                                  UIViewController *chatVC = [[UIViewController alloc]init];
                                  chatVC.title = title;
                                  
                                  [self.navigationController pushViewController:chatVC animated:YES];
                                  
                                  UIWebView *webV = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, screenW, screenH)];
                                  
                                  [chatVC.view addSubview:webV];
                                  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
                                  [webV loadRequest:request];
                              };
                          }
                              break;
                          case 2:
                          {
                              NSString *comboID = ad[@"parameter"];
                              imgV.clickAction = ^(){
                                  //push套餐控制器
                                  BPComboViewController *comboVC = [[BPComboViewController alloc]init];
                                  comboVC.comboID = comboID;
                                  [self.navigationController pushViewController:comboVC animated:YES];
                              };
                          }
                              break;
                              
                          default:
                              break;
                      }
                  }
                  [imgs addObject:imgV];
              }
              
              imgViewPlayer.views = imgs;
              
              [imgViewPlayer hidePageControl];
              
              [adView addSubview:imgViewPlayer];
              
              UITableView *comboTableView = [[UITableView alloc]init];
              self.comboTableView = comboTableView;
              comboTableView.tableHeaderView = adView;
              comboTableView.dataSource = self;
              comboTableView.delegate = self;
              
              comboTableView.clipsToBounds = NO;
              
              comboTableView.frame = CGRectMake(10, 10 + 64, screenW - 20, screenH - 20 - 64);
              comboTableView.backgroundColor = [UIColor clearColor];
              comboTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
              comboTableView.showsVerticalScrollIndicator = NO;
              [comboTableView registerNib:[UINib nibWithNibName:@"BPComboTableViewCell" bundle:nil] forCellReuseIdentifier:@"comboCell"];
              
              [self.view addSubview:comboTableView];
          }
          else {
              [SVProgressHUD showInfoWithStatus:@"广告数据获取失败"];
              dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                  [SVProgressHUD dismiss];
              });
          }
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          [SVProgressHUD showInfoWithStatus:@"请求失败"];
          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
              [SVProgressHUD dismiss];
          });
      }];
    
}

#pragma mark - table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BPComboTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"comboCell" forIndexPath:indexPath];
    cell.clipsToBounds = NO;
    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.name.text = self.data[indexPath.row][@"title"];
    cell.price.text = [NSString stringWithFormat:@"¥%@",self.data[indexPath.row][@"price"]];
    [cell.img sd_setImageWithURL:[NSURL URLWithString: self.data[indexPath.row][@"imgs"][0]] placeholderImage:[UIImage imageNamed:@"zhanweitu"]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return screenW / 375.0 * 274;
}

#pragma mark - table view delegate
//点击cell弹出套餐详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BPComboViewController *comboVC = [[BPComboViewController alloc]init];
    NSString *comboID = self.data[indexPath.row][@"id"];
    comboVC.comboID = comboID;
    [self.navigationController pushViewController:comboVC animated:YES];
    
}


#pragma mark LeftViewControllerDelegate


@end
